import { AppDataSource } from "@/config/database";
import { Customer } from "@/entities/basis/customer.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { TokenPayload } from "@/utils/token.util";
import { Context } from "koa";

export interface IBody extends Customer {
}

/** 创建客户 */
export async function createCustomer(ctx: Context) {
    const body = ctx.request.body as IBody;
    const user:TokenPayload = ctx.state.user;

    validateParams(body.code, body.name); // 校验参数
    await checkCustomerExists(body.phone, body.email); // 检查手机号和邮箱是否已存在

    // 创建客户
    const customer = await saveCustomer(body, user);

    ctx.status = 200;
    ctx.body = customer;
}

/** 校验参数 */
const validateParams = (code: string, name: string) => {
    if (!code) {
        throw new ErrorHandler('客户编号不能为空', 400);
    }
    if (!name) {
        throw new ErrorHandler('客户姓名不能为空', 400);
    }
}

/** 检查手机号和邮箱是否已存在 */
const checkCustomerExists = async (phone: string, email?: string) => {
    const customerRepository = AppDataSource.getRepository(Customer);

    // 检查手机号是否存在（如果提供了手机号）
    if (phone) {
        const existingPhone = await customerRepository.findOne({
            where: { phone }
        });
        if (existingPhone) {
            throw new ErrorHandler('手机号已存在', 409);
        }
    }

    // 检查邮箱是否存在（如果提供了邮箱）
    if (email) {
        const existingEmail = await customerRepository.findOne({
            where: { email }
        });
        if (existingEmail) {
            throw new ErrorHandler('邮箱已被注册', 409);
        }
    }
}

/** 保存客户到数据库 */
const saveCustomer = async (body: IBody, user: TokenPayload) => {
    
    const customerRepository = AppDataSource.getRepository(Customer);
    const customer = new Customer();

    // 必填字段
    customer.code = body.code.trim();
    customer.name = body.name.trim();
    customer.createdBy = user.id;
    customer.updatedBy = user.id;

    // 可选字段 - 添加数据验证
    if (body.phone) {
        customer.phone = body.phone.trim();
    }

    if (body.email) {
        customer.email = body.email.trim();
    }

    if (body.gender) {
        customer.gender = body.gender.trim();
    }

    if (body.hairType) {
        customer.hairType = body.hairType.trim();
    }

    if (body.scalpCondition) {
        customer.scalpCondition = body.scalpCondition.trim();
    }

    if (body.allergyHistory) {
        customer.allergyHistory = body.allergyHistory.trim();
    }

    if (body.preference) {
        customer.preference = body.preference.trim();
    }

    if (body.birthday) {
        customer.birthday = body.birthday;
    }

    try {
        return await customerRepository.save(customer);
    } catch (error) {
        // 处理数据库保存错误
        if (error.code === 'ER_DUP_ENTRY') {
            throw new ErrorHandler('客户编号已存在', 409);
        }
        throw new ErrorHandler('保存客户信息失败', 500);
    }
} 